<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Auth extends CI_Controller
{

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *         http://example.com/index.php/welcome
     *    - or -
     *         http://example.com/index.php/welcome/index
     *    - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function index()
    {
        //载入数据库
        $this->load->database();

        $result = $this->db->get('plan_item_tb')->result_array();

        $this->load->view('Plan', array(
            'planList' => $result,
        ));

    }


    //注册接口
    public function signUp(){
        //设置时区为RPC
        date_default_timezone_set("PRC");
        //用户名正则，目前只支持邮箱
        define('USERNAME_REG','/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/');
        
        //(必须包含大小写字母和数字的组合，可以使用特殊字符，长度在6-30之间)
        define('PASSWORD_REG','/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,30}$/');
        
        $OUTPUT=array();
        //获取去除空格后的登录用户名密码
        $nickname=trim($this->input->get('nickname'));
        $username=trim($this->input->get('username'));
        $password=trim($this->input->get('password'));
        
        //判断参数是否为空
        if(empty($nickname)||empty($username)||empty($password)){
            //参数不合法
            $OUTPUT['code']=-3;
            $OUTPUT['status']='Invalid parameter';
        }else{
            
            //用户名和密码或昵称不符合规范
            if(!preg_match(USERNAME_REG,$username)
                ||!preg_match(PASSWORD_REG,$password)
                ||!preg_match(USERNAME_REG,$nickname)){

                $OUTPUT['code']=-4;
                $OUTPUT['status']='Invalid username or password or nickname';
            }else{
                
                //拼接查询字符串
                $where='LOWER (email) = LOWER ("'.$username.'")';
                
                $this->load->database();
                $this->db->select('email')
                    ->from('user_item_tb')
                    ->where($where);

                $usernameRow=$this->db->get()->row();

                if($usernameRow){
                    $OUTPUT['code']=-2;
                    $OUTPUT['status']='Invalid username';
                }else{
                    //拼接查询字符串
                    $where='LOWER (nick_name) = LOWER ("'.$nickname.'")';

                    $this->db->select('nick_name')
                        ->from('user_item_tb')
                        ->where($where);

                    $nicknameRow=$this->db->get()->row();
                    
                    //
                    if($nicknameRow){
                        $OUTPUT['code']=-2;
                        $OUTPUT['status']='Invalid nickname';
                    }else{
                        $passwordHash=password_hash($password,PASSWORD_DEFAULT);
                        $data = array(
                            //邮箱统一转为小写，昵称以提交的为准
                            'email' => strtolower($username),
                            'nick_name' => $nickname,
                            'password'=>$passwordHash,
                            'create_date' => date("Y-m-d H:i:s",Time())
                        );
                        
                        $this->db->insert('user_item_tb', $data);
                        $OUTPUT['code']=1;
                        $OUTPUT['status']='Success';
                        $OUTPUT['userId']=$this->db->insert_id();
                    }
                }
            }
        }
        
        //返回结果
        header('content-type:application/json;charset=utf-8');
        echo json_encode($OUTPUT);
    }
    
    
    //登录接口
    public function signIn(){
        
        //用户名正则，目前只支持邮箱
        define('USERNAME_REG','/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/');
        
        //(必须包含大小写字母和数字的组合，可以使用特殊字符，长度在6-30之间)
        define('PASSWORD_REG','/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,30}$/');
        
        $OUTPUT=array();
        //获取去除空格后的登录用户名密码
        $username=trim($this->input->get('username'));
        $password=trim($this->input->get('password'));
        

        //判断参数是否为空
        if(empty($username)||empty($password)){
            //参数不合法
            $OUTPUT['code']=-3;
            $OUTPUT['status']='Invalid parameter';
        }else{ 
            //用户名和密码不符合规范
            if(!preg_match(USERNAME_REG,$username)
                ||!preg_match(PASSWORD_REG,$password)){

                $OUTPUT['code']=-4;
                $OUTPUT['status']='Invalid username or password';
            }else{
                

                $this->load->database();
                $row=$this->db->select('password')
                    ->get_where('user_item_tb', array('email' => $username))
                    ->row_array();
                $passwordHash=$row['password'];
                //如果查询结果为空，用户不存在
                if(is_null($passwordHash)){
                    $OUTPUT['code']=-2;
                    $OUTPUT['status']='Invalid username';
                }else{

                    //对密码hash进行校验
                    if (password_verify($password, $passwordHash)) {
                        
                        $this->load->library('session');
                        
                        //session存储登录信息
                        $_SESSION['username']=$username;
                        $OUTPUT['code']=1;
                        $OUTPUT['status']='Success';
                        
                    }else {
                        // Invalid 用户名密码不匹配
                        $OUTPUT['code']=-1;
                        $OUTPUT['status']='Incorrect username or password';
                    }
                }
            }
        }

        //返回结果
        header('content-type:application/json;charset=utf-8');
        echo json_encode($OUTPUT);
    }
    
    //退出接口
    public function signOut(){
        $this->load->library('session');
        //销毁session 退出登录
        $this->session->sess_destroy();
    }
    

    


    public function validate()
    {
        //$OUTPUT = array();
        //验证的字段类型
        $type = $this->input->get('type');

        switch ($type) {
            case 'username':
                $OUTPUT = $this->validateUser();
                break;
            case 'email':
                $OUTPUT = $this->validateEmail();
                break;
        }

        //返回结果
        header('content-type:application/json;charset=utf-8');
        echo json_encode($OUTPUT);
    }

    public function validateUser()
    {
        $OUTPUT = array();
        //获取去除空格后用户名称
        $userName = trim($this->input->post('username'));
        //用户昵称正则
        define('USERNAME_REG', '/^(?!\d+$)[\x{4e00}-\x{9fa5}a-z0-9]+_?[\x{4e00}-\x{9fa5}a-z0-9]+$/iu');
        if (empty($userName)) {
            //参数不合法
            $OUTPUT['code'] = -3;
            $OUTPUT['status'] = 'Invalid Parameter';
        } else if (!preg_match(USERNAME_REG, $userName) || strlen($userName) < 2 || strlen($userName) > 20) {
            $OUTPUT['code'] = -4;
            $OUTPUT['status'] = 'Non-conforman UserName';
        } else {

            //拼接查询字符串
            $where = 'LOWER (`username`) = LOWER ("' . $userName . '")';

            $this->load->database();
            $this->db->select('username')
                ->from('user_item_tb')
                ->where($where);

            $userNameRow = $this->db->get()->row();
            //用户名已存在
            if ($userNameRow) {
                $OUTPUT['code'] = -2;
                $OUTPUT['status'] = 'Invalid UserName';
            } else {
                $OUTPUT['code'] = 1;
                $OUTPUT['status'] = 'Success';
            }

        }

        return $OUTPUT;
    }

    public function validateEmail()
    {
        $OUTPUT = array();
        //获取去除空格后用户名称
        $email = trim($this->input->post('email'));
        //邮箱正则
        define('EMAIL_REG', '/^[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)+$/i');
        if (empty($email)) {
            //参数不合法
            $OUTPUT['code'] = -3;
            $OUTPUT['status'] = 'Invalid Parameter';
        } else if (!preg_match(EMAIL_REG, $email)) {
            $OUTPUT['code'] = -4;
            $OUTPUT['status'] = 'Non-conforman Email';
        } else {

            //拼接查询字符串
            $where = 'LOWER (`email`) = LOWER ("' . $email . '")';

            $this->load->database();
            $this->db->select('email')
                ->from('user_item_tb')
                ->where($where);

            $emailRow = $this->db->get()->row();
            //邮箱已存在
            if ($emailRow) {
                $OUTPUT['code'] = -2;
                $OUTPUT['status'] = 'Invalid UserName';
            } else {
                $OUTPUT['code'] = 1;
                $OUTPUT['status'] = 'Success';
            }

        }

        return $OUTPUT;
    }

}
